<template>
  <div class="offline-document-manager">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="breadcrumb-container">
        <div class="breadcrumb-scroll">
          <div class="breadcrumb" v-if="currentNode">
            <template v-if="currentPath.length <= 3">
              <span v-for="(item, index) in currentPath" :key="item.id">
                <span
                  @click="navigateToPath(item)"
                  class="breadcrumb-item"
                  :class="{ 'current-node': index === currentPath.length - 1 }"
                >
                  <el-icon class="breadcrumb-icon">
                    <Folder
                      v-if="
                        item.type === 'folder' && index < currentPath.length - 1
                      "
                    />
                    <FolderOpened v-else-if="item.type === 'folder'" />
                    <Document v-else />
                  </el-icon>
                  {{ item.label }}
                </span>
                <span v-if="index < currentPath.length - 1" class="separator">
                  <el-icon><ArrowRight /></el-icon>
                </span>
              </span>
            </template>
            <template v-else>
              <span
                @click="navigateToPath(currentPath[0])"
                class="breadcrumb-item"
              >
                <el-icon class="breadcrumb-icon">
                  <FolderOpened />
                </el-icon>
                {{ currentPath[0].label }}
              </span>
              <span class="separator">
                <el-icon><ArrowRight /></el-icon>
              </span>
              <el-tooltip
                effect="dark"
                :content="getMiddlePath()"
                placement="top"
              >
                <span class="breadcrumb-ellipsis">
                  <el-icon><MoreFilled /></el-icon>
                </span>
              </el-tooltip>
              <span class="separator">
                <el-icon><ArrowRight /></el-icon>
              </span>
              <span
                @click="navigateToPath(currentPath[currentPath.length - 1])"
                class="breadcrumb-item current-node"
              >
                <el-icon class="breadcrumb-icon">
                  <Document
                    v-if="
                      currentPath[currentPath.length - 1].type === 'document'
                    "
                  />
                  <FolderOpened v-else />
                </el-icon>
                {{ currentPath[currentPath.length - 1].label }}
              </span>
            </template>
          </div>
        </div>
      </div>
      <div class="actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文档或文件夹..."
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="action-buttons">
          <!-- 上传文件按钮 -->
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
            multiple
          >
            <el-tooltip content="上传文件" placement="bottom">
              <el-button type="primary" icon="Upload" circle />
            </el-tooltip>
          </el-upload>

          <!-- 新建操作下拉菜单 -->
          <el-dropdown trigger="click">
            <el-button type="primary" icon="Plus" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="addFolder(null)">
                  <el-icon><FolderAdd /></el-icon>
                  <span>新建文件夹</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 删除按钮 -->
          <el-tooltip content="删除" placement="bottom">
            <el-button
              type="danger"
              icon="Delete"
              circle
              @click="deleteItem"
              :disabled="!currentNode"
            />
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧树形目录 -->
      <div class="directory-tree-container">
        <div class="directory-tree">
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="treeProps"
            :filter-node-method="filterNode"
            node-key="id"
            highlight-current
            :expand-on-click-node="false"
            :default-expanded-keys="expandedKeys"
            draggable
            @node-drop="handleNodeDrop"
            @node-click="handleNodeClick"
            @node-contextmenu="handleContextMenu"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <el-icon v-if="data.type === 'folder'" class="folder-icon">
                  <FolderOpened v-if="node.expanded" />
                  <Folder v-else />
                </el-icon>
                <el-icon v-else class="document-icon">
                  <component :is="getFileIcon(data)" />
                </el-icon>

                <span
                  v-if="!data.editing"
                  class="node-label"
                  @dblclick="startRename(data)"
                >
                  {{ node.label }}
                </span>

                <el-input
                  v-else
                  ref="renameInput"
                  v-model="data.label"
                  size="small"
                  @blur="finishRename(data)"
                  @keyup.enter="finishRename(data)"
                />
              </div>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右侧文件列表区 -->
      <div class="file-list-panel">
        <div v-if="currentNode" class="file-list-content">
          <div class="file-list-header">
            <h2>{{ currentNode.label }}</h2>
            <div class="file-count">共 {{ filteredFiles.length }} 个文件</div>
          </div>

          <el-table
            :data="filteredFiles"
            style="width: 100%"
            empty-text="当前目录没有文件"
            @row-click="handleFileClick"
          >
            <el-table-column prop="label" label="文件名" min-width="200">
              <template #default="{ row }">
                <div class="file-name-cell">
                  <el-icon class="file-icon">
                    <component :is="getFileIcon(row)" />
                  </el-icon>
                  <span>{{ row.label }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="size" label="大小" width="120">
              <template #default="{ row }">
                {{ formatFileSize(row.size) }}
              </template>
            </el-table-column>
            <el-table-column prop="uploadDate" label="上传日期" width="180" />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  @click.stop="showPreview(row)"
                >
                  预览
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click.stop="deleteFile(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-else class="empty-preview">
          <el-icon class="empty-icon"><FolderOpened /></el-icon>
          <h3>选择文件夹查看内容</h3>
          <p>从左侧树形目录中选择文件夹查看其中的文件</p>
        </div>
      </div>
    </div>

    <!-- 节点操作菜单 -->
    <div
      v-if="contextMenuVisible"
      class="context-menu"
      :style="{ top: contextMenuY + 'px', left: contextMenuX + 'px' }"
      @mouseleave="contextMenuVisible = false"
    >
      <div v-if="currentNode.type === 'folder'" class="menu-section">
        <div class="menu-header">文件夹操作</div>
        <div class="menu-item" @click="addFolder('sibling')">
          <el-icon><FolderAdd /></el-icon>
          <span>添加同级文件夹</span>
        </div>
        <div class="menu-item" @click="addFolder('child')">
          <el-icon><FolderAdd /></el-icon>
          <span>添加子文件夹</span>
        </div>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="startRename">
          <el-icon><Edit /></el-icon>
          <span>重命名</span>
        </div>
        <div class="menu-item" @click="deleteFolder">
          <el-icon><Delete /></el-icon>
          <span>删除文件夹</span>
        </div>
      </div>

      <div v-else class="menu-section">
        <div class="menu-header">文件操作</div>
        <div class="menu-item" @click="showPreview(currentNode)">
          <el-icon><View /></el-icon>
          <span>预览文件</span>
        </div>
        <div class="menu-item" @click="startRename">
          <el-icon><Edit /></el-icon>
          <span>重命名</span>
        </div>
        <div class="menu-item" @click="deleteFile(currentNode)">
          <el-icon><Delete /></el-icon>
          <span>删除文件</span>
        </div>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="downloadFile(currentNode)">
          <el-icon><Download /></el-icon>
          <span>下载文件</span>
        </div>
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      :title="previewFile?.label"
      width="80%"
      top="5vh"
      destroy-on-close
      custom-class="preview-dialog"
    >
      <!-- 图片预览 -->
      <div v-if="previewType === 'image'" class="preview-container">
        <el-image
          style="max-height: 70vh; max-width: 100%"
          :src="getFileUrl(previewFile)"
          :preview-src-list="[getFileUrl(previewFile)]"
          fit="contain"
          :initial-index="0"
          :zoom-rate="1.2"
          :max-scale="10"
          :min-scale="0.1"
        />
      </div>

      <!-- PDF预览 -->
      <div v-else-if="previewType === 'pdf'" class="preview-container">
        <iframe
          :src="`/pdfjs/web/viewer.html?file=${encodeURIComponent(
            getFileUrl(previewFile)
          )}`"
          style="width: 100%; height: 70vh; border: none"
        ></iframe>
      </div>

      <!-- 文本文件预览 -->
      <div v-else-if="previewType === 'text'" class="preview-container">
        <el-scrollbar style="height: 70vh">
          <pre class="text-preview">{{ fileContent }}</pre>
        </el-scrollbar>
      </div>

      <!-- Office文档预览 -->
      <div v-else-if="previewType === 'office'" class="preview-container">
        <iframe
          :src="`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
            getFileUrl(previewFile)
          )}`"
          style="width: 100%; height: 70vh; border: none"
        ></iframe>
      </div>

      <!-- 视频预览 -->
      <div v-else-if="previewType === 'video'" class="preview-container">
        <video controls style="max-height: 70vh; max-width: 100%">
          <source
            :src="getFileUrl(previewFile)"
            :type="`video/${getFileExtension(previewFile)}`"
          />
          您的浏览器不支持视频预览
        </video>
      </div>

      <!-- 音频预览 -->
      <div v-else-if="previewType === 'audio'" class="preview-container">
        <audio controls style="width: 100%">
          <source
            :src="getFileUrl(previewFile)"
            :type="`audio/${getFileExtension(previewFile)}`"
          />
          您的浏览器不支持音频预览
        </audio>
      </div>

      <!-- 不支持的文件类型 -->
      <div v-else class="unsupported-preview">
        <el-icon :size="60"><Warning /></el-icon>
        <h3>不支持预览此文件类型</h3>
        <p>您可以下载后查看此文件</p>
      </div>

      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadFile(previewFile)">
          下载文件
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from "vue";
import {
  Folder,
  FolderOpened,
  Document,
  ArrowRight,
  MoreFilled,
  Search,
  Plus,
  FolderAdd,
  Upload,
  Delete,
  Edit,
  Download,
  VideoCamera,
  Picture,
  Headset,
  Collection,
  Tickets,
  View,
  Warning,
} from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();

// 树形目录数据示例
const treeData = ref([
  {
    id: "root",
    label: "我的文档",
    type: "folder",
    children: [
      {
        id: "projects",
        label: "项目文档",
        type: "folder",
        children: [
          {
            id: "project-plan",
            label: "项目计划书.docx",
            type: "document",
            fileType: "word",
            size: 2457600, // 2.4MB
            uploadDate: "2023-07-21 14:30",
            path: "/我的文档/项目文档/项目计划书.docx",
          },
          {
            id: "budget",
            label: "预算表.xlsx",
            type: "document",
            fileType: "excel",
            size: 1536000, // 1.5MB
            uploadDate: "2023-07-20 10:15",
            path: "/我的文档/项目文档/预算表.xlsx",
          },
          {
            id: "presentation",
            label: "项目介绍.pptx",
            type: "document",
            fileType: "ppt",
            size: 5120000, // 5MB
            uploadDate: "2023-07-18 16:45",
            path: "/我的文档/项目文档/项目介绍.pptx",
          },
        ],
      },
      {
        id: "reports",
        label: "报告",
        type: "folder",
        children: [
          {
            id: "monthly-report",
            label: "月度报告.pdf",
            type: "document",
            fileType: "pdf",
            size: 1024000, // 1MB
            uploadDate: "2023-07-22 09:20",
            path: "/我的文档/报告/月度报告.pdf",
          },
          {
            id: "analysis",
            label: "数据分析.xlsx",
            type: "document",
            fileType: "excel",
            size: 2150400, // 2.1MB
            uploadDate: "2023-07-19 11:20",
            path: "/我的文档/报告/数据分析.xlsx",
          },
        ],
      },
      {
        id: "images",
        label: "图片",
        type: "folder",
        children: [
          {
            id: "sample-image",
            label: "示例图片.jpg",
            type: "document",
            fileType: "image",
            size: 102400, // 100KB
            uploadDate: "2023-07-22 11:30",
            path: "/我的文档/图片/示例图片.jpg",
          },
          {
            id: "diagram",
            label: "架构图.png",
            type: "document",
            fileType: "image",
            size: 512000, // 500KB
            uploadDate: "2023-07-23 14:15",
            path: "/我的文档/图片/架构图.png",
          },
        ],
      },
      {
        id: "notes",
        label: "笔记",
        type: "folder",
        children: [
          {
            id: "readme",
            label: "说明.txt",
            type: "document",
            fileType: "text",
            size: 1024,
            uploadDate: "2023-07-23 09:00",
            path: "/我的文档/笔记/说明.txt",
            content:
              "这是一个示例文本文件\n用于演示文件预览功能\n第二行内容\n第三行内容",
          },
        ],
      },
      {
        id: "videos",
        label: "视频",
        type: "folder",
        children: [
          {
            id: "demo-video",
            label: "演示视频.mp4",
            type: "document",
            fileType: "video",
            size: 10485760, // 10MB
            uploadDate: "2023-07-24 10:45",
            path: "/我的文档/视频/演示视频.mp4",
          },
        ],
      },
    ],
  },
  {
    id: "shared",
    label: "共享文档",
    type: "folder",
    children: [
      {
        id: "team-docs",
        label: "团队文档",
        type: "folder",
        children: [
          {
            id: "guidelines",
            label: "团队指南.docx",
            type: "document",
            fileType: "word",
            size: 3072000, // 3MB
            uploadDate: "2023-07-17 13:20",
            path: "/共享文档/团队文档/团队指南.docx",
          },
        ],
      },
    ],
  },
  {
    id: "personal-cv",
    label: "个人简历.pdf",
    type: "document",
    fileType: "pdf",
    size: 1024000, // 1MB
    uploadDate: "2023-07-22 09:20",
    path: "/个人简历.pdf",
  },
]);

// 预览相关状态
const previewVisible = ref(false);
const previewFile = ref(null);
const previewType = ref("");
const fileContent = ref("");

// 显示文件预览
const showPreview = async (file) => {
  previewFile.value = file;
  const ext = getFileExtension(file);

  // 根据文件扩展名设置预览类型
  if (["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(ext)) {
    previewType.value = "image";
  } else if (ext === "pdf") {
    previewType.value = "pdf";
  } else if (["doc", "docx", "xls", "xlsx", "ppt", "pptx"].includes(ext)) {
    previewType.value = "office";
  } else if (["txt", "json", "js", "css", "html", "xml", "md"].includes(ext)) {
    previewType.value = "text";
    if (file.content) {
      fileContent.value = file.content;
    } else {
      fileContent.value = await getFileContent(file);
    }
  } else if (["mp4", "avi", "mov", "wmv", "webm"].includes(ext)) {
    previewType.value = "video";
  } else if (["mp3", "wav", "aac", "ogg"].includes(ext)) {
    previewType.value = "audio";
  } else {
    previewType.value = "unsupported";
  }

  previewVisible.value = true;
  contextMenuVisible.value = false;
};

// 获取文件扩展名
const getFileExtension = (file) => {
  return file.label.split(".").pop().toLowerCase();
};

// 获取文件URL（实际项目中需要根据你的文件存储方式实现）
const getFileUrl = (file) => {
  // 示例代码，实际项目中需要替换为真实的文件访问URL
  return `/api/files/${file.id}`;
};

// 获取文本文件内容（实际项目中需要从服务器获取）
const getFileContent = async (file) => {
  try {
    // 模拟从服务器获取文本内容
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(
          `这是文件 ${file.label} 的模拟内容\n文件路径: ${
            file.path
          }\n文件大小: ${formatFileSize(file.size)}\n上传时间: ${
            file.uploadDate
          }`
        );
      }, 300);
    });
  } catch (error) {
    console.error("获取文件内容失败:", error);
    return "无法加载文件内容";
  }
};

// 树形配置
const treeProps = ref({
  label: "label",
  children: "children",
});

// 当前选中的节点
const currentNode = ref(null);
// 搜索查询
const searchQuery = ref("");
// 树形组件引用
const treeRef = ref(null);
// 重命名输入框引用
const renameInput = ref(null);

// 默认展开的节点
const expandedKeys = ref(["root", "projects", "reports", "images", "shared"]);

// 上下文菜单控制
const contextMenuVisible = ref(false);
const contextMenuX = ref(0);
const contextMenuY = ref(0);

// 计算当前路径
const currentPath = computed(() => {
  const path = [];
  if (!currentNode.value) return path;

  const findPath = (nodes, targetId) => {
    for (const node of nodes) {
      if (node.id === targetId) {
        path.unshift(node);
        return true;
      }
      if (node.children) {
        if (findPath(node.children, targetId)) {
          path.unshift(node);
          return true;
        }
      }
    }
    return false;
  };

  findPath(treeData.value, currentNode.value.id);
  return path;
});

// 获取中间路径的完整内容
const getMiddlePath = () => {
  if (currentPath.value.length <= 3) return "";
  return currentPath.value
    .slice(1, -1)
    .map((item) => item.label)
    .join(" / ");
};

// 获取当前目录下的文件列表
const filteredFiles = computed(() => {
  if (!currentNode.value || currentNode.value.type !== "folder") return [];

  let files = (currentNode.value.children || []).filter(
    (item) => item.type === "document"
  );

  // 应用搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    return files.filter((file) => file.label.toLowerCase().includes(query));
  }

  return files;
});

// 根据文件类型获取对应的图标
const getFileIcon = (file) => {
  if (file.type === "folder") {
    return Folder;
  }

  const fileType = file.fileType || "";
  const ext = file.label.split(".").pop().toLowerCase();

  // 根据文件类型或扩展名返回对应图标
  if (fileType === "word" || ext === "doc" || ext === "docx") {
    return Document;
  } else if (fileType === "excel" || ext === "xls" || ext === "xlsx") {
    return Collection;
  } else if (fileType === "ppt" || ext === "ppt" || ext === "pptx") {
    return Tickets;
  } else if (ext === "pdf") {
    return Document;
  } else if (["jpg", "jpeg", "png", "gif", "bmp"].includes(ext)) {
    return Picture;
  } else if (["mp4", "avi", "mov", "wmv"].includes(ext)) {
    return VideoCamera;
  } else if (["mp3", "wav", "aac"].includes(ext)) {
    return Headset;
  } else if (["txt", "md", "json", "js", "css", "html", "xml"].includes(ext)) {
    return Document;
  } else {
    return Document;
  }
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 处理树节点点击
const handleNodeClick = (data) => {
  // 只有当点击的是文件夹节点时才更新 currentNode
  if (data.type === "folder") {
    currentNode.value = data;
  }
};

// 处理文件点击
const handleFileClick = (file) => {
  showPreview(file);
};

// 导航到路径
const navigateToPath = (item) => {
  treeRef.value.setCurrentKey(item.id);
  currentNode.value = item;
};

// 过滤树节点
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.toLowerCase().includes(value.toLowerCase());
};

// 监听搜索查询变化
watch(searchQuery, (val) => {
  treeRef.value.filter(val);
});

// 处理节点拖放
const handleNodeDrop = (draggingNode, dropNode, dropType) => {
  console.log(
    `节点 ${draggingNode.data.label} 被移动到 ${dropType} ${dropNode.data.label}`
  );
};

// 处理右键菜单
const handleContextMenu = (event, data, node, element) => {
  event.preventDefault();
  currentNode.value = data;
  contextMenuX.value = event.clientX;
  contextMenuY.value = event.clientY;
  contextMenuVisible.value = true;
  treeRef.value.setCurrentKey(data.id);
};

// 添加文件夹
const addFolder = (position) => {
  const newFolder = {
    id: `folder-${Date.now()}`,
    label: "新建文件夹",
    type: "folder",
    children: [],
    editing: true,
  };

  if (!position) {
    // 添加到根节点
    treeData.value.push(newFolder);
    expandedKeys.value.push(newFolder.id);
    treeRef.value.setCurrentKey(newFolder.id);
    return;
  }

  if (!currentNode.value) return;

  if (currentNode.value.type === "folder") {
    if (position === "sibling") {
      // 添加到同级
      const parent = treeRef.value.getNode(currentNode.value).parent;
      if (parent.level === 0) {
        // 根节点
        treeData.value.splice(
          treeData.value.indexOf(currentNode.value) + 1,
          0,
          newFolder
        );
      } else {
        parent.data.children.splice(
          parent.data.children.indexOf(currentNode.value) + 1,
          0,
          newFolder
        );
      }
    } else if (position === "child") {
      // 添加到子节点
      if (!currentNode.value.children) currentNode.value.children = [];
      currentNode.value.children.push(newFolder);
      treeRef.value.setCurrentKey(newFolder.id);
    }
    expandedKeys.value.push(newFolder.id);
  }

  // 设置新文件夹为编辑状态
  nextTick(() => {
    newFolder.editing = true;
    treeRef.value.setCurrentKey(newFolder.id);
    setTimeout(() => {
      if (renameInput.value) {
        renameInput.value.focus();
      }
    }, 50);
  });
};

// 开始重命名
const startRename = () => {
  if (currentNode.value) {
    currentNode.value.editing = true;
    contextMenuVisible.value = false;

    nextTick(() => {
      if (renameInput.value) {
        renameInput.value.focus();
      }
    });
  }
};

// 完成重命名
const finishRename = (node) => {
  node.editing = false;
};

// 删除文件夹
const deleteFolder = () => {
  if (!currentNode.value || currentNode.value.type !== "folder") return;

  const confirm = window.confirm(
    `确定要删除文件夹 "${currentNode.value.label}" 及其所有内容吗？`
  );
  if (!confirm) return;

  // 递归删除节点
  const deleteNode = (nodes, id) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        nodes.splice(i, 1);
        return true;
      }
      if (nodes[i].children) {
        if (deleteNode(nodes[i].children, id)) {
          return true;
        }
      }
    }
    return false;
  };

  deleteNode(treeData.value, currentNode.value.id);
  contextMenuVisible.value = false;
};

// 查找文档的父文件夹
const findParentFolder = (id) => {
  const findParent = (nodes) => {
    for (const node of nodes) {
      if (node.children) {
        for (const child of node.children) {
          if (child.id === id) {
            return node;
          }
        }
        const parent = findParent(node.children);
        if (parent) return parent;
      }
    }
    return null;
  };
  return findParent(treeData.value);
};

// 删除项目（文件或文件夹）
const deleteItem = () => {
  if (!currentNode.value) return;

  const confirm = window.confirm(
    `确定要删除 "${currentNode.value.label}" 吗？`
  );
  if (!confirm) return;

  // 删除节点
  const deleteNode = (nodes, id) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        nodes.splice(i, 1);
        return true;
      }
      if (nodes[i].children) {
        if (deleteNode(nodes[i].children, id)) {
          return true;
        }
      }
    }
    return false;
  };

  deleteNode(treeData.value, currentNode.value.id);
  currentNode.value = null;
};

// 删除文件
const deleteFile = (file) => {
  if (!file) return;

  const confirm = window.confirm(`确定要删除文件 "${file.label}" 吗？`);
  if (!confirm) return;

  // 查找并删除文件
  const deleteFileNode = (nodes, id) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        nodes.splice(i, 1);
        return true;
      }
      if (nodes[i].children) {
        if (deleteFileNode(nodes[i].children, id)) {
          return true;
        }
      }
    }
    return false;
  };

  deleteFileNode(treeData.value, file.id);

  // 如果删除的是当前选中的文件
  if (currentNode.value?.id === file.id) {
    currentNode.value = null;
  }

  contextMenuVisible.value = false;
  proxy.$modal.msgSuccess(`文件 "${file.label}" 已删除`);
};

// 下载文件
const downloadFile = (file) => {
  if (!file) return;

  // 这里模拟下载操作，实际应用中需要根据文件路径或内容生成下载链接
  const link = document.createElement("a");
  link.href = `#${file.id}`; // 实际应用中替换为真实文件URL
  link.download = file.label;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  proxy.$modal.msgSuccess(`开始下载文件 "${file.label}"`);
};

// 文件上传前的验证
const beforeUpload = (file) => {
  const allowedTypes = [
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-powerpoint",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    "application/pdf",
    "image/jpeg",
    "image/png",
    "image/gif",
    "video/mp4",
    "audio/mpeg",
    "text/plain",
  ];

  const isAllowed = allowedTypes.includes(file.type);
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isAllowed) {
    proxy.$modal.msgError("不支持上传此类型文件!");
  }
  if (!isLt10M) {
    proxy.$modal.msgError("文件大小不能超过10MB!");
  }

  return isAllowed && isLt10M;
};

// 处理文件上传
const handleUpload = (options) => {
  const { file } = options;
  const parentId =
    currentNode.value?.type === "folder" ? currentNode.value.id : null;

  // 创建新文件节点
  const newFile = {
    id: `file-${Date.now()}`,
    label: file.name,
    type: "document",
    fileType: getFileType(file),
    size: file.size,
    uploadDate: new Date().toLocaleString(),
    path: parentId ? `${currentNode.value.path}/${file.name}` : `/${file.name}`,
  };

  // 如果是文本文件，读取内容
  if (file.type.startsWith("text/")) {
    const reader = new FileReader();
    reader.onload = (e) => {
      newFile.content = e.target.result;
    };
    reader.readAsText(file);
  }

  // 添加到树形结构中
  if (parentId) {
    // 添加到当前文件夹
    const addToFolder = (nodes) => {
      for (const node of nodes) {
        if (node.id === parentId) {
          if (!node.children) node.children = [];
          node.children.push(newFile);
          return true;
        }
        if (node.children) {
          if (addToFolder(node.children)) {
            return true;
          }
        }
      }
      return false;
    };

    addToFolder(treeData.value);
  } else {
    // 添加到根目录
    treeData.value.push(newFile);
  }

  proxy.$modal.msgSuccess(`文件 "${file.name}" 上传成功`);
};

// 根据文件类型返回分类
const getFileType = (file) => {
  const type = file.type;
  const ext = file.name.split(".").pop().toLowerCase();

  if (type.includes("word") || ext === "doc" || ext === "docx") {
    return "word";
  } else if (type.includes("excel") || ext === "xls" || ext === "xlsx") {
    return "excel";
  } else if (type.includes("powerpoint") || ext === "ppt" || ext === "pptx") {
    return "ppt";
  } else if (type.includes("pdf") || ext === "pdf") {
    return "pdf";
  } else if (type.includes("image")) {
    return "image";
  } else if (type.includes("video")) {
    return "video";
  } else if (type.includes("audio")) {
    return "audio";
  } else if (type.includes("text") || ["txt", "md"].includes(ext)) {
    return "text";
  } else {
    return "other";
  }
};

// 查找树中的第一个文件夹
const findFirstFolder = (nodes) => {
  for (const node of nodes) {
    if (node.type === "folder") {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const folder = findFirstFolder(node.children);
      if (folder) return folder;
    }
  }
  return null;
};

// 模拟数据加载
onMounted(() => {
  // 默认选中第一个文件夹
  setTimeout(() => {
    const firstFolder = findFirstFolder(treeData.value);
    if (firstFolder) {
      treeRef.value.setCurrentKey(firstFolder.id);
      currentNode.value = firstFolder;
    }
  }, 100);

  // 点击其他地方关闭上下文菜单
  document.addEventListener("click", () => {
    contextMenuVisible.value = false;
  });
});
</script>

<style scoped>
.offline-document-manager {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
  font-family: "Helvetica Neue", Arial, sans-serif;
  position: relative;
}

.header {
  background: white;
  padding: 15px 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 10;
  flex-shrink: 0;
}

.breadcrumb-container {
  flex: 1;
  overflow: hidden;
  margin-right: 20px;
}

.breadcrumb-scroll {
  overflow-x: auto;
  white-space: nowrap;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.breadcrumb-scroll::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.breadcrumb {
  display: inline-flex;
  align-items: center;
  font-size: 16px;
  padding-bottom: 2px; /* 为滚动条留空间 */
}

.breadcrumb-item {
  cursor: pointer;
  color: #606266;
  padding: 4px 6px;
  border-radius: 4px;
  max-width: 200px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s;
}

.breadcrumb-item.current-node {
  font-weight: 500;
  color: var(--el-color-primary);
  cursor: default;
}

.breadcrumb-icon {
  margin-right: 6px;
  font-size: 16px;
}

.breadcrumb-item:hover:not(.current-node) {
  color: #409eff;
  background-color: #f5f7fa;
}

.breadcrumb-ellipsis {
  cursor: pointer;
  color: #606266;
  padding: 4px 6px;
  border-radius: 4px;
  display: inline-flex;
  align-items: center;
}

.breadcrumb-ellipsis:hover {
  color: #409eff;
  background-color: #f5f7fa;
}

.separator {
  margin: 0 8px;
  color: #c0c4cc;
  display: inline-flex;
  align-items: center;
}

.actions {
  display: flex;
  align-items: center;
}

.search-input {
  width: 240px;
  margin-right: 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .el-button {
  margin-left: 0 !important;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  padding: 20px;
  gap: 20px;
}

.directory-tree-container {
  flex: 0 0 280px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.directory-tree {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow-y: auto;
  border: 1px solid #ebeef5;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 5px 0;
  position: relative;
}

.tree-node .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.tree-node .folder-icon {
  color: #e6a23c;
}

.tree-node .document-icon {
  color: #409eff;
}

.node-label {
  flex: 1;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: default;
}

.file-list-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.file-list-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.file-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.file-list-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.file-count {
  color: #909399;
  font-size: 14px;
}

.file-name-cell {
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 8px;
  font-size: 18px;
}

.empty-preview {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  color: #c0c4cc;
}

.empty-preview h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #606266;
}

.empty-preview p {
  margin: 0 0 20px 0;
  font-size: 14px;
}

/* 上下文菜单 */
.context-menu {
  position: fixed;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  width: 200px;
  overflow: hidden;
}

.menu-section {
  padding: 8px 0;
}

.menu-header {
  padding: 8px 16px;
  font-size: 12px;
  color: #909399;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 4px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.menu-item:hover {
  background: #f5f7fa;
}

.menu-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.menu-divider {
  height: 1px;
  background: #ebeef5;
  margin: 6px 0;
}

/* 表格样式 */
:deep(.el-table) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

:deep(.el-table__body-wrapper) {
  flex: 1;
  overflow: auto;
}

:deep(.el-table .cell) {
  padding-left: 12px;
  padding-right: 12px;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

/* 树形目录样式 */
:deep(.el-tree) {
  background-color: transparent;
}

:deep(.el-tree-node__content) {
  height: 36px;
  border-radius: 4px;
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: #f0f7ff;
}

:deep(
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
  ) {
  background-color: #f0f7ff;
  font-weight: 500;
}

/* 上传按钮样式 */
:deep(.el-upload) {
  display: inline-block;
}

/* 文件图标颜色 */
.word-icon {
  color: #2b579a;
}

.excel-icon {
  color: #217346;
}

.ppt-icon {
  color: #d24726;
}

.pdf-icon {
  color: #e53935;
}

.image-icon {
  color: #ff7043;
}

.video-icon {
  color: #7b1fa2;
}

.audio-icon {
  color: #009688;
}

/* 预览相关样式 */
.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  width: 100%;
}

.unsupported-preview {
  text-align: center;
  padding: 40px 0;
  color: var(--el-color-warning);
}

.unsupported-preview h3 {
  margin: 20px 0 10px;
}

.text-preview {
  white-space: pre-wrap;
  font-family: monospace;
  padding: 20px;
  background: #f8f8f8;
  border-radius: 4px;
  margin: 0;
}

:deep(.preview-dialog) {
  display: flex;
  flex-direction: column;
}

:deep(.preview-dialog .el-dialog__body) {
  flex: 1;
  padding: 0;
}

:deep(.preview-dialog .el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .main-content {
    flex-direction: column;
  }

  .directory-tree-container {
    flex: 0 0 300px;
    width: 100%;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .breadcrumb-container {
    margin-right: 0;
    width: 100%;
  }

  .actions {
    width: 100%;
    justify-content: space-between;
  }

  .search-input {
    flex: 1;
  }
}
</style>
